<template>
  <!-- 登录界面路由 -->
  <div class="login-view">
    <!-- 版心 -->
    <div class="container">
      <div class="login">
        <div>
          <div class="f1">
            <span :class="{ active: now == 0 }" @click="now = 0">账号登录</span
            >|
            <span :class="{ active: now == 1 }" @click="now = 1">短信登录</span>
          </div>
          <div class="f2">
            <!-- 用户名 -->
             <el-input
                    v-show="now == 0"
                    v-model.trim="uname"
                    placeholder="请输入邮箱/用户名"
                    type="text"
                    @blur="checkUname"
                    autocomplete="off"
                    clearable
                  ></el-input>
            <p v-show="!unm" class="yzn">
              {{ now == 0 ? "请检查用户名!" : "请检查手机号" }}
            </p>

            <!-- 手机号 -->
             <el-input
                      v-show="now == 1"
                      v-model.trim="uphone"
                      placeholder="请输入手机号"
                      type="text"
                      @blur="checkPhone"
                    autocomplete="off"
                    clearable
                  ></el-input>
            <!-- 密码 -->
             <el-input
                    type="password"
                    v-model.trim="upwd"
                    autocomplete="off"
                    clearable
                    :placeholder="now == 0 ? '请输入密码' : '请输入短信验证码'"
                    show-password
                     @blur="checkUpwd"
                  ></el-input>
            <p v-show="!upw" class="yzw">
              {{ now == 0 ? "请检查密码!" : "请检查短信验证码!" }}
            </p>
          </div>
          <!-- 验证码 -->
          <div id="yan-zheng">
              <el-input
                    id="yanzhen"
                    v-model="yz"
                    type="text"
                    placeholder="请输入验证码"
                    @blur="checkYz"
                    autocomplete="off"
                    clearable
                  ></el-input>
            <p v-show="!yzm">请检查验证码!</p>
            <canvas id="canvas" width="120" height="40" @click="clear"></canvas>
          </div>
          <div class="f4">
            <button @click="checkForm">登录</button>
          </div>
          <div class="f5">
            <!-- <label><input type="checkbox" /> 7天内自动登录</label> -->
            <label></label>
            <div>
              <span>忘记密码?</span>&nbsp;|&nbsp;
              <span><router-link to="/register">注册</router-link></span>
            </div>
          </div>
          <!-- <div class="f6">第三方账号登录</div> -->
          <div class="f7">
            <img src="" alt="" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  computed: {},
  data() {
    return {
      uname: "", // 存储用户名
      upwd: "", // 存储密码
      uphone: "", // 存储手机号
      now: 0,
      num: null, //定义容器接收验证码
      yz: null,
      unm: true, // 用户名/手机号提示信息状态
      upw: true, // 密码提示信息状态
      yzm: true, // 验证码提示信息状态
      avatar:"https://pic.imoe.pw/2022/10/15/f7f6d58558d65.png",    //默认头像图片地址
      pan_duan1:false,   //判断是否登录
    };
  },
  methods: {
    checkPhone() {
      // 验证手机号
      let exp = /^1[3-9]\d{9}$/;
      if (exp.test(this.uphone)) {
        console.log("手机号合规");
        return (this.unm = true);
      } else {
        console.log("请检查手机号格式!");

        return (this.unm = false);
      }
    },
    checkUpwd() {
      // 验证密码  (以字母开头，长度在6~18之间，只能包含字母、数字和下划线)
      // let exp = /^[a-zA-Z]\w{5,17}$/;

      // 验证密码(长度在6~18之间)
       let exp = /^\w{6,17}$/;
      if (exp.test(this.upwd)) {
        console.log("密码合法");
        return (this.upw = true);
      } else {
        // this.upwd = "";
        console.log("密码非法");
        return (this.upw = false);
      }
    },
    checkUname() {
      // 验证账号 (字母开头，允许5-16字节，允许字母数字下划线)
      // let exp = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
       // 验证账号(长度在6~18之间)
       let exp = /^\w{6,17}$/;
      if (exp.test(this.uname)) {
        console.log("用户名合法");
        return (this.unm = true);
      } else {
        console.log("用户名非法");

        return (this.unm = false);
      }
    },
    checkForm() {
      let cn = this.checkUname();
      let cw = this.checkUpwd();
      let cy = this.checkYz();
      console.log(cn, cw, cy);
      if (cn && cw && cy) {
         let params = `uname=${this.uname}&upwd=${this.upwd}`;
        this.axios.post("/login", params).then((res) => {
          console.log(res);
          // console.log(res.data.results.avatar);
          if (res.data.code == 200) {
            // console.log("登陆成功...后续操作");
            this.$message({
                  message: '登录成功!',
                  type: 'success',
                  offset:110,
                  duration:1500,
            });   
            // 1.5秒后进行跳转
            setTimeout(() => {
              // 调用mutations的方法，修改vuex中的登录用户名
              this.$store.commit('updateName',res.data.results.user_name)
              // 调用mutations的方法，修改vuex中的头像
              this.$store.commit('upheadPhoto',res.data.results.avatar)
              // if(res.data.results.state==0){
                // 登录状态为true
                this.pan_duan1=true
                this.$store.commit('uloginState',this.pan_duan1)
              // }
              
              // 跳转到首页
              this.$router.push('/')
            }, 1550);
          } else {
            // console.log("登录失败...");
             this.$message({
                  message: '登录失败！请检查用户名与密码',
                  type: 'error',
                  offset:110,
                  duration:3000,
            });   
            // 清空验证码输入框的内容并且刷新验证码
            this.yz=''
            this.clear();
          }
        });
        
      } else {
       console.log("登录失败");
      }
    },

    // 检查验证码
    checkYz() {
      if (this.yz == this.num) {
        console.log("验证成功");
        return (this.yzm = true);
      } else {
        console.log("验证失败");
        return (this.yzm = false);
      }
    },
    // 清理验证码 并生成新的验证码
    clear() {
      var canvas = document.getElementById("canvas"); //演员
      var context = canvas.getContext("2d"); //舞台，
      context.clearRect(0, 0, 120, 40); //在给定的矩形内清除指定的像素
      this.draw();
    },
    // 随机颜色函数
    getColor() {
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      return "rgb(" + r + "," + g + "," + b + ")";
    },

    // 生成验证码函数
    draw() {
      var canvas = document.getElementById("canvas"); //演员
      var context = canvas.getContext("2d"); //舞台，
      context.strokeRect(0, 0, 120, 40); //绘制矩形（无填充）
      var aCode = [
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "a",
        "b",
        "c",
        "d",
        "e",
        "f",
      ];
      // 绘制字母
      var arr = []; //定义一个数组用来接收产生的随机数
      for (var i = 0; i < 4; i++) {
        var x = 20 + i * 20; //每个字母之间间隔20
        var y = 20 + 10 * Math.random(); //y轴方向位置为20-30随机
        var index = Math.floor(Math.random() * aCode.length); //随机索引值
        var txt = aCode[index];
        context.font = "bold 20px 微软雅黑"; //设置或返回文本内容的当前字体属性
        context.fillStyle = this.getColor(); //设置或返回用于填充绘画的颜色、渐变或模式，随机
        context.translate(x, y); //重新映射画布上的 (0,0) 位置，字母不可以旋转移动，所以移动容器
        var deg = (90 * Math.random() * Math.PI) / 180; //0-90度随机旋转
        context.rotate(deg); // 	旋转当前绘图
        context.fillText(txt, 0, 0); //在画布上绘制“被填充的”文本
        context.rotate(-deg); //将画布旋转回初始状态
        context.translate(-x, -y); //将画布移动回初始状态
        arr[i] = txt; //接收产生的随机数
      }
      this.num = arr[0] + arr[1] + arr[2] + arr[3]; //将产生的验证码放入num
      // 绘制干扰线条
      for (var i = 0; i < 8; i++) {
        context.beginPath(); //起始一条路径，或重置当前路径
        context.moveTo(Math.random() * 120, Math.random() * 40); //把路径移动到画布中的随机点，不创建线条
        context.lineTo(Math.random() * 120, Math.random() * 40); //添加一个新点，然后在画布中创建从该点到最后指定点的线条
        context.strokeStyle = this.getColor(); //随机线条颜色
        context.stroke(); // 	绘制已定义的路径
      }
      // 绘制干扰点，和上述步骤一样，此处用长度为1的线代替点
      for (var i = 0; i < 20; i++) {
        context.beginPath();
        var x = Math.random() * 120;
        var y = Math.random() * 40;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.strokeStyle = this.getColor();
        context.stroke();
      }
    },
  },
  mounted() {
    this.draw();
  },
};
</script>

<style lang="scss">
.el-input .el-input__inner{
  border:none;
  border-bottom: 1px solid #d7d7d7;
}
</style>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
}
input {
  outline: none;
  border: none;
  padding: 10px 15px;
  border-bottom: 1px solid #d7d7d7;
}
.login-view {
  background-color: #fff6f6;
  height: 800px;

  > .container {
    width: 800px;
    height: 800px;
    margin: 0 auto;
    position: relative;

    > .login {
      background-color: #fff;
      width: 420px;
      height: 420px;
      position: absolute;
      right: 50%;
      top: 50%;
      transform: translate(50%, -50%);
      padding: 30px;
      box-sizing: border-box;
      display: flex;
      justify-content: center;
      > div {
        > div {
          width: 300px;
          box-sizing: border-box;
          display: flex;
          justify-content: center;
        }
        > .f1 {
          display: flex;
          margin-bottom: 30px;
          color: #d7d7d7;

          > span {
            font-size: 20px;
            font-weight: bold;
            display: block;
            padding: 0 15px;
            cursor: pointer;
            color: black;

            &.active {
              color: #f84b4b;
            }
          }
        }

        > .f2 {
          height: 100px;
          flex-wrap: wrap;
          margin-bottom: 30px;
          position: relative;
          > .el-input{
            height: 42px;
            width: 300px;
            display: block;
            box-sizing: border-box;
            margin-bottom: 20px;
          }

          > .yzp,
          .yzn {
            font-size: 12px;
            color: red;
            position: absolute;
            top: 45px;
            left: 15px;
          }

          > .yzw {
            font-size: 12px;
            color: red;
            position: absolute;
            top: 105px;
            left: 15px;
          }
        }

        > .f4 {
          position: relative;
          margin-bottom: 25px;
          > button {
            width: 300px;
            box-sizing: border-box;
            height: 42px;
            border: none;
            border-radius: 20px;
            background-color: #ff6e6e;
            color: #fff;
            user-select: none;
            cursor: pointer;
          }
         > button:hover{
            opacity: 0.85;
          }
        }

        > .f5 {
          margin-top: 10px;
          justify-content: space-between;
          color: #808080;
          font-size: 12px;
          margin-bottom: 30px;

          > label {
            user-select: none;
          }
        }

        > .f6 {
          justify-content: center;
          color: #808080;
          margin-bottom: 15px;
        }

        > .f7 {
          > img {
            display: block;
            margin: 0 auto;
          }
        }
      }
    }
  }
}
#yan-zheng {
  width: 300px;
  height: 42px;
  display: flex;
  position: relative;
  margin-bottom: 30px;

  > input {
    padding-left: 15px;
    width: 60%;
    border: none;
    border-bottom: 1px solid #d7d7d7;
    outline: none;
  }
  > p {
    font-size: 12px;
    color: red;
    position: absolute;
    top: 45px;
    left: 15px;
  }
}
</style>